package com.hskj.springboot.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

//@Configuration
public class RabbitMQDLXConfig {
    //定义交换机的名称和队列名称
    public static final String EXCHANGE_F_DLX_NAME = "boot_dlx_exchange";
    //死信交换机
    public static final String EXCHANGE_DLX_NAME = "dlx_exchange";
    public static final String QUEUE_F_DLX_NAME = "boot_dlx_queue";
    //死信队列
    public static final String QUEUE_DLX_NAME = "dlx_queue";

    /*
    * 配置正常交换机
    * */
    @Bean("bootDlxExchange")
    public Exchange springDlxExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_F_DLX_NAME).durable(true).build();
    }
    /*
     * 配置死信交换机
     * */
    @Bean("dlxExchange")
    public Exchange springboootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_DLX_NAME).durable(true).build();
    }
    /*
     * 配置正常队列
     * */
    @Bean("bootDLXQueue")
    public Queue springbootQueue(){
        HashMap<String, Object> dlxMap = new HashMap<>();
        //x-message-ttl 指的是过期时间
        dlxMap.put("x-message-ttl",10000);
        //x-max-length  指的是队列最大数
        dlxMap.put("x-max-length",10);
        //x-dead-letter-exchange 指的是死信交换机
        dlxMap.put("x-dead-letter-exchange",RabbitMQDLXConfig.EXCHANGE_DLX_NAME);
        //x-dead-letter-routing-key 指的是死信routingKey
        dlxMap.put("x-dead-letter-routing-key","dlx.hehe");
        return QueueBuilder.durable(QUEUE_F_DLX_NAME).withArguments(dlxMap).build();
    }
    /*
     * 配置死信队列
     * */
    @Bean("dlxQueue")
    public Queue springdlxQueue(){
        return QueueBuilder.durable(QUEUE_DLX_NAME).build();
    }
    /*
    * 绑定正常交换机和队列
    * */
    @Bean
    public Binding QueueBindingExchange(@Qualifier("bootDLXQueue") Queue queue,@Qualifier("bootDlxExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.dlx.#").noargs();
    }
    /**
     *死信队列和死信交换机绑定关系
     * 1. 知道哪个队列
     * 2. 知道哪个交换机
     * 3. routing key
     *
     */
    @Bean
    public Binding bindDlxQueueExchange(@Qualifier("dlxQueue") Queue queue,@Qualifier("dlxExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("dlx.#").noargs();
    }
}
